package com.chhuang.utils.string;

import java.io.UnsupportedEncodingException;

import org.bouncycastle.util.encoders.Base64;


/**
 * base64编码工具
 * @author 程秀超
 * @date 2013-4-2
 *
 */
public final class Base64Util {
	
	/**
	 * 编码
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		String result = StringUtil.EMPTY_STR;
		
		if(StringUtil.isNotEmpty(str)) {
			result =  new String(Base64.encode(str.getBytes()));
		}
		
		return result;
	}
	
	/**
	 * 编码
	 * @param bytes
	 * @return
	 */
	public static String encode(byte[] bytes) {
		String result = StringUtil.EMPTY_STR;
		
		if(bytes!=null && bytes.length>0) {
			result =  new String(Base64.encode(bytes));
		}
		
		return result;
	}
	
	/**
	 * 指定字符集编码
	 * @param str
	 * @param charset
	 * @return
	 */
	public static String encode(String str, String charset) {
		String result = StringUtil.EMPTY_STR;
		
		if(StringUtil.isNotEmpty(str)) {
			if(StringUtil.isEmpty(charset)) {
				charset = StringEncoding.CHARSET_UTF8;
			}
			try {
				result =  new String(Base64.encode(str.getBytes(charset)), charset);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	/**
	 * 解码
	 * @param str
	 * @return
	 */
	public static String decode(String str) {
		String result = StringUtil.EMPTY_STR;
		
		if(StringUtil.isNotEmpty(str)) {
			result =  new String(Base64.decode(str.getBytes()));
		}
		
		return result;
	}
	
	/**
	 * 根据指定字符集解码
	 * @param str
	 * @param charset
	 * @return
	 */
	public static String decode(String str, String charset) {
		String result = StringUtil.EMPTY_STR;
		
		if(StringUtil.isNotEmpty(str)) {
			if(StringUtil.isEmpty(charset)) {
				charset = StringEncoding.CHARSET_UTF8;
			}
			try {
				result =  new String(Base64.decode(str.getBytes(charset)), charset);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}
}
